const usersModel = require('../models/users');
const jwt = require('jsonwebtoken');
const fs = require('fs');
const path = require('path');


const {
  hash,
  compare,
  setCookie,
  sign,
  verify
} = require('../utils/tools');

//注册用户
const signup = async (req, res, next) => {
  //设置请求头
  res.set('content-type', 'application/json; charset=utf-8');
  //拿到表单的用户信息
  const {
    username,
    password
  } = req.body;

  //密码加密
  const bcryptPassword = await hash(password);

  //判断数据库里用户是否存在
  let findResult = await usersModel.findUser(username);
  //用户存在
  if (findResult) {
    //提示错误的渲染模板
    res.render('fail', {
      data: JSON.stringify({
        message: '用户名已存在'
      })
    })
  } else {
    //用户不存在
    //将用户信息存入数据库
    let result = await usersModel.signup({
      username,
      password: bcryptPassword
    });

    //将用户信息渲染到成功的模板
    //res.render('模板名字', 数据);
    res.render('succ', {
      data: JSON.stringify({
        message: '注册成功！'
      })
    });
  }


}

//用户列表
const list = async (req, res, next) => {
  //设置请求头
  res.set('content-type', 'application/json; charset=utf-8');
  const listResult = await usersModel.findList();
  res.render('succ', {
    data: JSON.stringify(listResult)
  });
}

//删除用户
const remove = async (req, res, next) => {
  //设置请求头
  res.set('content-type', 'application/json; charset=utf-8');
  const {
    id
  } = req.body;
  const result = await usersModel.remove(id);
  if (result) {
    res.render('succ', {
      data: JSON.stringify({
        message: '用户删除成功!'
      })
    });
  } else {
    res.render('fail', {
      data: JSON.stringify({
        message: '用户删除失败!'
      })
    });
  }

}

//用户登录
const signin = async (req, res, next) => {
  const {
    username,
    password
  } = req.body;
  let findResult = await usersModel.findUser(username);
  //验证用户是否是合法用户
  if (findResult) {
    //校验密码
    let {
      //别名
      password: hash
    } = findResult;
    let compareResult = await compare(password, hash);
    if (compareResult) {
      // //设置sessionId存入Cookie
      // setCookie(res);
      //设置cookie-session
      // req.session.username = username;

      //公钥私钥的token
      const token = sign(username);
      // console.log(token);
      //自定义请求头携带参数为token
      res.set('X-Access-Token', token);

      res.render('succ', {
        data: JSON.stringify({
          username,
          message: '登录成功!'
        })
      });

      //密码错误
    } else {
      res.render('fail', {
        data: JSON.stringify({
          message: '用户名或者密码错误！'
        })
      });
    }
    //用户名错误
  } else {
    res.render('fail', {
      data: JSON.stringify({
        message: '用户名或者密码错误！'
      })
    });
  }
}

//退出登录
const signout = async (req, res, next) => {
  req.session = null;
  res.render('succ', {
    data: JSON.stringify({
      message: '退出登录成功!'
    })
  });
}

//session
const isAuth = async (req, res, next) => {
  //拿到前端传过来的token
  let token = req.get('X-Access-Token');
  try {
    //验证token
    let result = verify(token);
    res.render('succ', {
      data: JSON.stringify({
        username: result.username
      })
    });
  } catch (e) {
    res.render('fail', {
      data: JSON.stringify({
        message: 'X-Access-Token信息失效，请登录!'
      })
    });
  }


  // 用户信息有效
  // if (req.session.username) {
  //   res.render('succ', {
  //     data: JSON.stringify({
  //       username: req.session.username
  //     })
  //   });
  // } else {
  //   res.render('fail', {
  //     data: JSON.stringify({
  //       message: '用户信息失效，请登录!'
  //     })
  //   });
  // }
}

//token
// const token = (req, res, next) => {
//   //对称加密
//   const tk = jwt.sign({
//     username: 'admin'
//   }, 'hahaha');
//   const decoded = jwt.verify(tk, 'hahaha');
//   res.send(decoded);

//   //非对称加密
//   const privateKey = fs.readFileSync(path.join(__dirname, '../keys/rsa_private_key.pem'));
//   const tk = jwt.sign({
//     username: 'admin'
//   }, privateKey);

//   const publicKey = fs.readFileSync(path.join(__dirname, '../keys/rsa_public_key.pem'));
//   const result = jwt.verify(tk, publicKey);

//   res.send(result);
// }

const token = (req, res, next) => {}


module.exports = {
  signup,
  list,
  remove,
  signin,
  signout,
  isAuth,
  token
};